# -*- coding: utf-8 -*-
'''
Created on 2014年3月3日

@author: jun.chn@gmail.com
'''
import subprocess
import sys

def cmd_util(cmd):
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    res = p.stdout.readlines()
    if p.wait() == 0:
        return res
    return False
'''
活动连接

  协议  本地地址          外部地址        状态           PID
  TCP    0.0.0.0:135            0.0.0.0:0              LISTENING       932
  TCP    0.0.0.0:445            0.0.0.0:0              LISTENING       4
  TCP    0.0.0.0:554            0.0.0.0:0              LISTENING       5740
'''
class netstat(object):
    cmd = ('netstat',  '-nao')
    LISTENING = 'LISTENING'
    def __init__(self, cols):
        self.proto, self.local, self.foreign, self.state, self.PID = cols
    @classmethod
    def create(cls, line):
        cols = line.split()
        if len(cols) == 5:
            return netstat(cols)
        return None
    @classmethod        
    def make(cls):
        res = []
        lines = cmd_util(cls.cmd)
        for line in lines:
            net = netstat.create(line)
            if net and net.state == cls.LISTENING:
                res.append(net)
        return res
    def __str__(self):
        return '%s %s' % (self.proto, self.local)

'''
映像名称                       PID 会话名              会话#       内存使用  状态            用户名                                                 CPU 时间 窗口标题
========================= ======== ================ =========== ============ =============== ================================================== ============ ========================================================================
System                           4 Services                   0      2,208 K Unknown         暂缺                                                    0:01:59 暂缺
'''
class tasklist(object):
    cmd = ('tasklist', '/fo', 'table', '/v', '/fi', "pid eq %s" )
    def __init__(self, line):
        self.image_name, self.PID, self.session_name, self.session_id, self.use_memory, self.use_memory_unit,self.status, self.user,self.cpu_time, self.windows_name = line.split()
#         self.user = self.user.decode("gbk")
    @classmethod
    def create(cls, line):
        cols = line.split()
        if len(cols) == 10: 
            return tasklist(line)
        return None
    @classmethod        
    def make(cls, pids):
        res = []
        for pid in pids:
            lines = cmd_util(cls.cmd[:-1] + (cls.cmd[-1] % pid,))
            task = cls.create(lines[-1])
            if task:
                res.append(task)
        return sorted(res, key=lambda task : int(task.PID)) 
    def __str__(self):
        return "%s %s" % (self.PID, self.image_name)
     
class cport(object):
    def __init__(self):
        self.load()
    
    def load(self):
        self.nets = netstat.make() 
        self.tasks = tasklist.make(set([net.PID for net in self.nets]))
    
    def display(self):
        for task in self.tasks:
            print '[PID=%s]' % task
            for net in self.nets:
                if task.PID == net.PID:
                    print '\t%s' % net 
    def display_list(self):
        print '\t'.join(['PID','NAME','PROTO','LOCAL'])
        for task in self.tasks:
            for net in self.nets:
                if task.PID == net.PID:
                    print '%s\t%s\t%s\t%s' % (task.PID, task.image_name, net.proto, net.local) 

def setUtf8():
    reload(sys)
    sys.setdefaultencoding('utf-8')  # @UndefinedVariable

if __name__ == '__main__':
    setUtf8()
    obj = cport()
    if len(sys.argv) > 1 and sys.argv[1].upper() == '-L':
        obj.display_list()
    else:
        obj.display()
